//
//  XSM3u8DownloadViewController.m
//  XSDownloadDemo
//
//  Created by 大帅 on 2023/12/29.
//

#import "XSM3u8DownloadViewController.h"

#import "XSM3u8TableViewCell.h"        // cell
#import "XSPlayViewController.h"       // 播放页面
#import "XSDownloadBotView.h"          // 底部全选 / 删除

// cell标识符
static NSString *m3u8TableViewCellId = @"XSM3u8TableViewCellId";

@interface XSM3u8DownloadViewController () <UITableViewDelegate, UITableViewDataSource>
/** 列表视图 */
@property (nonatomic, strong) UITableView *tableView;
/** 导航右侧编辑按钮 */
@property (nonatomic, strong) UIButton *editBtn;
/** 数据 */
@property (nonatomic, strong) NSMutableArray *dataArray;
/** 全选 / 删除 */
@property (nonatomic, strong) XSDownloadBotView *botmView;
/** 多选删除数据集合 */
@property (nonatomic, strong) NSMutableArray *deleteArray;

@end

@implementation XSM3u8DownloadViewController

-(NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
        NSArray *list = [[XSDataSaveManager sharedManager] lookDownloadAllData];
        [_dataArray addObjectsFromArray:list];
    }
    return _dataArray;
}

-(NSMutableArray *)deleteArray {
    if (!_deleteArray) {
        _deleteArray = [[NSMutableArray alloc] init];
    }
    return _deleteArray;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 添加通知
    [self addNotification];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"download - list";
    self.view.backgroundColor = UIColor.orangeColor;
    
    // 编辑
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithCustomView:self.editBtn];
    self.navigationItem.rightBarButtonItem = rightButton;
    
    [self createViewUI];
    
}

- (void)addNotification {
    // 下载进度
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downLoadProgress:) name:XSDownloadM3u8ProgressNotification object:nil];
    // 下载状态改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downLoadStateChange:) name:XSDownloadM3u8StateNotification object:nil];
}

-(void)createViewUI {
    
    [self.view addSubview:self.botmView];
    [self.botmView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).offset(GK_TABBAR_HEIGHT);
        make.height.mas_equalTo(GK_TABBAR_HEIGHT);
    }];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.botmView.mas_top);
        make.top.mas_equalTo(GK_STATUSBAR_NAVBAR_HEIGHT);
    }];
}

// 编辑
-(UIButton *)editBtn {
    if (!_editBtn) {
        _editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _editBtn.frame = CGRectMake(0, 0, 50, 44);
        [_editBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        _editBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_editBtn setTitle:@"编辑" forState:UIControlStateNormal];
        [_editBtn setTitle:@"取消" forState:UIControlStateSelected];
        [_editBtn addTarget:self action:@selector(downEditBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _editBtn;
}

-(XSDownloadBotView *)botmView {
    if (!_botmView) {
        _botmView = [[XSDownloadBotView alloc] init];
        // 全选 / 取消
        __weak typeof(self) weakSelf = self;
        _botmView.botViewAllSelectBlock = ^(BOOL isSelect) {
            [weakSelf clickAllSelDataBtn:isSelect];
        };
        // 删除
        _botmView.botViewDeleteBlock = ^{
            [weakSelf clickDeleteDataHandle];
        };
    }
    return _botmView;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.allowsMultipleSelectionDuringEditing = YES;
        if (@available(iOS 11.0,*)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        [_tableView registerClass:[XSM3u8TableViewCell class] forCellReuseIdentifier:m3u8TableViewCellId];
    }
    return _tableView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 65;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        XSTestModel *delModel = [[XSDataSaveManager sharedManager] lookDownloadSingleData:self.dataArray[indexPath.row]];
        if (delModel) {
            // 删除当前指定下载任务
            if ([[XSDownloadManagerM3u8 sharedManager] deleteDownloadingTask:delModel]) {
                [self.dataArray removeObjectAtIndex:indexPath.row];
                [self.tableView reloadData];
            }
        }
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XSM3u8TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:m3u8TableViewCellId forIndexPath:indexPath];
    if (self.dataArray.count > indexPath.row) {
        cell.model = [self.dataArray objectAtIndex:indexPath.row];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    XSTestModel *downloadModel = [self.dataArray objectAtIndex:indexPath.row];
    // 编辑状态返回
    if (tableView.editing) {
        // 记录要删除的数据
        [self.deleteArray addObject:downloadModel];
        // 更新全选按钮 / 删除数量
        [self updateAllButtonText];
        return;
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 检查下载状态
    switch (downloadModel.state) {
        case XSDownloadStatusFinish: {
            
            NSLog(@"\n当前播放视频：%@\n路径：%@", downloadModel.videoName, downloadModel.locaM3u8lUrl);
            
            // 当前视频已下载完成，点击跳转播放页面
            XSPlayViewController *vc = [[XSPlayViewController alloc] init];
            vc.isM3u8 = YES;
            vc.modelM3u8 = downloadModel;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case XSDownloadStatusDownloading:
            // 当前视频正在下载中，点击暂停下载
            [[XSDownloadManagerM3u8 sharedManager] pauseDownloadingTask:downloadModel];
            break;
            
        case XSDownloadStatusWaiting:
            // 当前视频等待下载中，点击暂停下载
            [[XSDownloadManagerM3u8 sharedManager] pauseDownloadingTask:downloadModel];
            break;
            
        case XSDownloadStatusPause:
            // 当前视频暂停中，点击加入下载队列开始下载
            [[XSDownloadManagerM3u8 sharedManager] addDownloadingTask:downloadModel];
            break;
            
        case XSDownloadStatusError:
            // 当前视频下载错误，点击加入下载队列重新下载
            [[XSDownloadManagerM3u8 sharedManager] addDownloadingTask:downloadModel];
            break;
            
        default:
            break;
    }
}

// table编辑状态下取消选中
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    XSTestModel *downloadModel = [self.dataArray objectAtIndex:indexPath.row];
    // 取消要删除的数据
    [self.deleteArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        XSTestModel *model = (XSTestModel *)obj;
        if ([model.videoId isEqualToString:downloadModel.videoId]) {
            [self.deleteArray removeObjectAtIndex:idx];
            *stop = YES;
        }
    }];
    
    // 更新全选按钮 / 删除数量
    [self updateAllButtonText];
}

// 更新全选按钮 / 删除数量
-(void)updateAllButtonText {
    BOOL isSel = NO;
    if (self.dataArray.count > 0) {
        isSel = self.deleteArray.count == self.dataArray.count;
    }
    [self.botmView updateAllButtonSelect:isSel delNum:self.deleteArray.count];
}

#pragma mark -- 下载信息通知
// 下载进度
- (void)downLoadProgress:(NSNotification *)noti {
    XSTestModel *downloadModel = noti.object;
    // 更新数据以及UI
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        XSTestModel *model = (XSTestModel *)obj;
        if ([model.videoId isEqualToString:downloadModel.videoId]) {
            model = downloadModel;
            self.dataArray[idx] = model;
            // 主线程更新cell进度
            dispatch_async(dispatch_get_main_queue(), ^{
                XSM3u8TableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
                cell.model = downloadModel;
            });
            *stop = YES;
        }
    }];
}

// 下载状态改变
- (void)downLoadStateChange:(NSNotification *)noti {
    XSTestModel *downloadModel = noti.object;
    // 更新数据以及UI
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        XSTestModel *model = (XSTestModel *)obj;
        if ([model.videoId isEqualToString:downloadModel.videoId]) {
            model = downloadModel;
            self.dataArray[idx] = model;
            // 主线程更新cell进度
            dispatch_async(dispatch_get_main_queue(), ^{
                XSM3u8TableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
                cell.model = downloadModel;
            });
            *stop = YES;
        }
    }];
}

// 编辑按钮响应
-(void)downEditBtn:(UIButton *)sender {
    // 检查是否有数据
    if (!sender.selected && self.dataArray.count <= 0) {
        [[XSToastView shareManager] showMessage:@"暂无数据"];
        return;
    }
    
    sender.selected = !sender.selected;
    // 先退出编辑状态，防止进入编辑状态不对
    [self.tableView setEditing:NO animated:YES];
    // table编辑状态
    if (sender.isSelected) {
        [self.tableView setEditing:sender.selected animated:YES];
    }
    
    [self.botmView mas_updateConstraints:^(MASConstraintMaker *make) {
        if (sender.selected) {
            make.bottom.mas_equalTo(self.view);
        } else {
            make.bottom.mas_equalTo(self.view).offset(GK_TABBAR_HEIGHT);
        }
    }];
    [UIView animateWithDuration:0.2 animations:^{
        [self.view layoutIfNeeded];
    }];
    
    // 清空要删除的数据集合
    [self.deleteArray removeAllObjects];
    // 更新全选按钮 / 删除数量
    [self updateAllButtonText];
}

// 全选数据处理
-(void)clickAllSelDataBtn:(BOOL)isSel {
    // 检查是否有数据
    if (isSel && self.dataArray.count <= 0) {
        [[XSToastView shareManager] showMessage:@"暂无数据"];
        return;
    }
    
    if (isSel) {
        // 刷新cell选中状态
        for (int i = 0; i < self.dataArray.count; i ++) {
            NSIndexPath *selectIndex = [NSIndexPath indexPathForItem:i inSection:0];
            [self.tableView selectRowAtIndexPath:selectIndex animated:YES scrollPosition:UITableViewScrollPositionNone];
        }
        // 记录要删除的数据
        [self.deleteArray removeAllObjects];
        [self.deleteArray addObjectsFromArray:self.dataArray];
    } else {
        // 取消cell选中状态
        for (int i = 0; i < self.dataArray.count; i ++) {
            NSIndexPath *selectIndex = [NSIndexPath indexPathForItem:i inSection:0];
            [self.tableView deselectRowAtIndexPath:selectIndex animated:YES];
        }
        // 清空要删除的数据集合
        [self.deleteArray removeAllObjects];
    }
    // 更新全选按钮 / 删除数量
    [self updateAllButtonText];
}

// 删除数据
-(void)clickDeleteDataHandle {
    if (self.deleteArray.count > 0) {
        // 删除完成以后
        if ([[XSDownloadManagerM3u8 sharedManager] deleteMoreListTask:self.deleteArray]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 更新列表
                NSArray *list = [[XSDataSaveManager sharedManager] lookDownloadAllData];
                [self.dataArray removeAllObjects];
                [self.dataArray addObjectsFromArray:list];
                [self.tableView reloadData];
                
                // 清空要删除的数据集合
                [self.deleteArray removeAllObjects];
                // 更新全选按钮 / 删除数量
                [self updateAllButtonText];
            });
        }
    } else {
        [[XSToastView shareManager] showMessage:@"没有选中要删除的数据"];
    }
}

- (void)dealloc {
    NSLog(@"dealloc - %@", self.class);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
